<template>
    <button @click="threadPoxi">ceshi</button>
</template>

<script>

    import {baseUtil} from '@/util/BaseUtil';

    export default {
        name: "el-chat",
        data() {
            return {
                baseUtil : baseUtil,
                baseData : baseUtil.getBaseData(),
            }
        },
        methods : {
            threadPoxi(){  // 实际调用的方法
                // 参数
                const agentData = "mymessage";
                // 若是ws开启状态
                if (this.websock.readyState === this.websock.OPEN) {
                    this.websocketsend(agentData);
                }
                // 若是 正在开启状态，则等待300毫秒
                else if (this.websock.readyState === this.websock.CONNECTING) {
                    let that = this;//保存当前对象this
                    setTimeout(function () {
                        that.websocketsend(agentData);
                    }, 300);
                }
                // 若未开启 ，则等待500毫秒
                else {
                    this.initWebSocket();
                    let that = this;//保存当前对象this
                    setTimeout(function () {
                        that.websocketsend(agentData);
                    }, 500);
                }
            },
            // 初始化weosocket
            initWebSocket(id){
                // ws地址
                const wsuri = this.baseData.WEB_SOCKET_ADDRESS + id;
                this.websock = new WebSocket(wsuri);
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onclose = this.websocketclose;
            },
            // 数据接收
            websocketonmessage(e){
                const redata = JSON.parse(e.data);
                console.log(redata);
            },
            // 数据发送
            websocketsend(agentData){
                this.websock.send(agentData);
            },
            // 关闭
            websocketclose(e){
                console.log("connection closed (" + e.code + ")");
            }
        },
        created() {
            // 验证是否登录
            // 初始化webSocket
            this.initWebSocket(1);
        }
    }
</script>

<style scoped>

</style>
